import base64
import io
import random

from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import Mapped, mapped_column
from captcha.image import ImageCaptcha
import json

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../stu.db'
db = SQLAlchemy(app)


# db.session.execute("select * from stu_info")
class StuInfo(db.Model):
    __tablename__ = 'stu_info'
    sid: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(unique=False, nullable=False)
    sex: Mapped[int] = mapped_column()
    class_name: Mapped[str] = mapped_column(unique=False, nullable=False)
    phone: Mapped[str] = mapped_column(unique=False, nullable=False)
    grade: Mapped[int] = mapped_column(unique=False, nullable=False)
    major_name: Mapped[str] = mapped_column(unique=False, nullable=False)
    college_name: Mapped[str] = mapped_column(unique=False, nullable=False)
    email: Mapped[str] = mapped_column(unique=False, nullable=False)
    password: Mapped[str] = mapped_column(unique=False, nullable=False)
    header: Mapped[str] = mapped_column(unique=False, nullable=False)


currentUser = {'sid': None, 'name': None, 'header': None}


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/login')
def login():
    number = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'I',
              'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    str = ''.join(random.sample(number, 6))
    image = ImageCaptcha().generate_image(str)
    image_byte = io.BytesIO()
    image.save(image_byte, "jpeg")
    image_base64_str = 'data:image/jpeg;base64,' + base64.b64encode(image_byte.getvalue()).decode('utf-8')
    return render_template('index/login.html', captcha=image_base64_str)

@app.route('/captcha')
def generate_image():
    number = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'I',
              'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    str = ''.join(random.sample(number, 6))
    image = ImageCaptcha().generate_image(str)
    image_byte = io.BytesIO()
    image.save(image_byte, "jpeg")
    image_base64_str = 'data:image/jpeg;base64,' + base64.b64encode(image_byte.getvalue()).decode('utf-8')
    return image_base64_str

@app.route('/logout', methods=['post', 'get'])
def logout():
    global currentUser
    currentUser = {'sid': None, 'name': None, 'header': None}
    result = {"code": 200, "data": '', "msg": "退出操作成功"}
    if request.method == 'POST':
        return result
    else:
        return redirect("/login")


@app.route('/index')
def index():
    if currentUser['sid'] is None:
        return redirect("/login")
    else:
        return render_template("index/index.html", user=currentUser)
@app.route('/endMenu')
def endMenu():
        return render_template("index/menu1.html")

@app.route('/frontendMenu')
def endMenu():
    return render_template("index/menu2.html")

@app.route('/danyeList')
def danyeList():
        return render_template("index/article-list.html")


@app.route('/danyeList')
def danyeList():
        return render_template("index/article-list.html")

@app.route('/welcome')
def welcome():
    return render_template("index/welcome.html")


@app.route('/admin_info')
def admin_info():
    sid = request.args.get("sid")
    user = StuInfo.query.get(sid)
    return render_template("index/admin-info.html", adminInfo=user)


@app.route('/updateAdminInfo', methods=['post'])
def updateAdminInfo():
    sid = request.form.get("sid")
    name = request.form.get("name")
    email = request.form.get("email")
    desc = request.form.get("desc")
    updateUser = StuInfo.query.get(sid)
    updateUser.name = name
    updateUser.email = email
    updateUser.desc = desc
    db.session.commit()
    db.session.close()

    msg = ""
    result = {"code": 200, "data": None, "msg": ""}
    if updateUser:
        msg = '修改成功'
        result['msg'] = msg
        # return render_template("index/index.html",loginUser=stu)
    else:
        msg = '修改失败！'
        result['code'] = 201
        result['msg'] = msg
    return result


@app.route('/updateAdminPassword', methods=['post'])
def updateAdminPassword():
    sid = request.form.get("sid")
    password1 = request.form.get("password1")
    password2 = request.form.get("password2")
    password3 = request.form.get("password3")
    updateUser = StuInfo.query.get(sid)
    result = {"code": 200, "data": None, "msg": ""}
    code = 200
    if updateUser.password != password1:
        code = 201
        msg = '旧密码不正确！'
    elif password2 != password3:
        code = 202
        msg = '两次新密码输入不一致！'
    elif password2 == password1:
        code = 203
        msg = '旧密码和新密码不能相同！'
    else:
        updateUser.password = password2
        db.session.commit()
        db.session.close()
        msg = '修改成功'
    result['code'] = code
    result['msg'] = msg
    return result


@app.route('/gologin', methods=['post'])
def gologin():
    userName = request.form.get("userName")
    password = request.form.get("password")
    print(userName, password)
    # 从数据库中查询一条记录，来对比是否正确
    # stus = db.session.execute(db.select(StuInfo))
    # stus = db.session.execute(db.select(StuInfo)).scalars()
    # 查询所有 stus = StuInfo.query.all();
    # 按条件查询 stu = StuInfo.query.filter(StuInfo.sid == userName)
    # 按条件查询 stu = StuInfo.query.filter_by(sid = userName)
    # stus = StuInfo.query.all();
    # for stu in stus:
    #     print(stu.name)

    stu = StuInfo.query.filter(StuInfo.sid == userName, StuInfo.password == password).first()
    msg = ""
    result = {"code": 200, "data": None, "msg": ""}
    if stu:
        msg = '登录成功'
        result['msg'] = msg
        currentUser['sid'] = userName
        currentUser['name'] = stu.name
        currentUser['header'] = stu.header
        # return render_template("index/index.html",loginUser=stu)
    else:
        msg = '用户名或密码错误,请重新登录！'
        result['code'] = 201
        result['msg'] = msg
    return result
    # return render_template("loginerror.html")


if __name__ == '__main__':
    app.run()
